from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import UserCenterInfoSerializer, UserEmailSerializer

from users.models import User


class RegisterUsernameAPIView(APIView):
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        data = {
            'count':count,
            'username':username
        }
        return Response(data)

# 注册的实现
from users.serializers import RegisterUserSerializer,UserCenterInfoSerializer


class RegisterUserAPIView(APIView):
    def post(self,request):
        # 接收数据
        data=request.data
        #校验数据
        serializer = RegisterUserSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        #　数据入库
        # print(serializer.data)
        serializer.save()
        #返回响应
        return Response(serializer.data)

from rest_framework.generics import RetrieveAPIView
from rest_framework.permissions import IsAuthenticated


class UserCenterInfoAPIView(APIView):
    # 既然是登录用户,我们就要用到权限管理


    permission_classes = [IsAuthenticated]
    """
    获取登录用户的信息
    GET /users/
    既然是登录用户,我们就要用到权限管理
    在类视图对象中也保存了请求对象request
    request对象的user属性是通过认证检验// ., \]
    0 之后的请求用户对象

    """
    def get(self,request):
        #获取用户的信息
        user = request.user
            # 将对想转化为字典
        serializer=UserCenterInfoSerializer(user)
        #         返回响应
        return Response(serializer.data)

#     邮箱的实现
class UserEmailAPIView(APIView):
    permission_classes = [IsAuthenticated]
    def put(self,request):
        # 接收数据
        data=request.data
        # 校验数据

        serializer= UserEmailSerializer(instance=request.user,data=data)
        serializer.is_valid(raise_exception=True)
        # 更新数据　　　更新用put
        serializer.save()
        return Response(serializer.data)























# Create your views here.
